package com.share.advice;


import com.share.constant.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 如果方法返回的是ResponseEntity类型，或者含有@ResponseBody注解，则在通过消息映射器进行转换前，会调用该类中的方法处理响应体
 */
@RestControllerAdvice
@Slf4j
public class RestResponseBodyAdvice implements ResponseBodyAdvice {

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        log.info("returnType:{}", returnType);
        log.info("converterType:{}", converterType);
        // 获取请求路径
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            return true; // 如果没有请求上下文，返回 true
        }
        String path = attributes.getRequest().getRequestURI();

        // 排除 Swagger 相关路径
        if (path.startsWith("/v3/api-docs") || path.startsWith("/swagger-ui/index.html")|| path.equals("/user/getCaptcha")|| path.equals("/file/download")) {
            return false;
        }
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        log.info("body:{}", body);
        log.info("selectedContentType:{}", selectedContentType);
        log.info("selectedConverterType:{}", selectedConverterType);
//当响应体的类型不是ResponseEntity，并且响应体不是Result类型，则进行包装返回
        if (!(body instanceof ResponseEntity) && !(body instanceof Result) && !(body instanceof String)) {
            return Result.ok(body);
        }
        return body;
    }
}
